package org.jash.apps.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.lody.virtual.remote.InstalledAppInfo
import com.tencent.bugly.crashreport.CrashReport
import io.virtualapp.hook_sdk.app.InstallAppUtils
import kotlinx.coroutines.launch
import org.jash.apps.R
import org.jash.apps.BR
import org.jash.apps.databinding.ActivityLocalBinding
import org.jash.apps.entity.LocalEntity
import org.jash.apps.model.LocalIndent
import org.jash.apps.model.LocalState
import org.jash.apps.model.LocalViewModel
import org.jash.common.adapter.CommonAdapter
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseActivity

@Route(path = "/apps/local")
class LocalActivity : BaseActivity<ActivityLocalBinding, LocalViewModel>() {
    private val adapter by lazy { CommonAdapter<LocalEntity>({R.layout.item_local to BR.local}) }
    private val installAppUtils by lazy { InstallAppUtils() }
    private val edited = ObservableBoolean(false)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.recycler.adapter = adapter
        binding.edited = edited
        lifecycleScope.launch {
            viewModel.intent.send(LocalIndent.LoadLocalApp)
        }
        adapter.setOnItemClickListener {
            if(edited.get()) {
                MaterialAlertDialogBuilder(this)
                    .setTitle("确认删除")
                    .setMessage("是否确认删除${it.app.packageName}")
                    .setNegativeButton("否", null)
                    .setPositiveButton("是") { d, _ ->
                        if (installAppUtils.unInstallApp(it.app.packageName)) {
                            adapter -= it
                        } else {
                            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
                        }
                        d.cancel()
                    }
                    .show()
            } else {
                installAppUtils.launchApp(it.app.packageName)
            }
        }
    }
    fun loaded(res:LocalState.Response) {
        res.data.forEach(this::logDebug)
        adapter += res.data.map { LocalEntity(it, edited) }
    }
}